package com.example.gw_back_end.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gw_back_end.domain.entities.PostLike;
import com.example.gw_back_end.mapper.PostLikeMapper;
import com.example.gw_back_end.service.PostLikeService;
import com.example.gw_back_end.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements PostLikeService {

    private final PostLikeMapper postLikeMapper;
    public PostLikeServiceImpl(PostLikeMapper postLikeMapper) {
        this.postLikeMapper = postLikeMapper;
    }

    @Override
    public boolean addPostLike(Integer postId) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        PostLike postLike = new PostLike();
        postLike.setPostId(postId);
        postLike.setUserId(userId);
        postLike.setLikeTime(LocalDateTime.now());
        return postLikeMapper.insert(postLike) > 0;
    }

    @Override
    public boolean deletePostLike(Integer postId) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        LambdaQueryWrapper<PostLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PostLike::getPostId, postId);
        lambdaQueryWrapper.eq(PostLike::getUserId, userId);
        return postLikeMapper.delete(lambdaQueryWrapper) > 0;
    }

    @Override
    public boolean getPostLikeByPost(Integer postId) {
        Map<String,Object> claims= ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        LambdaQueryWrapper<PostLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PostLike::getPostId, postId);
        lambdaQueryWrapper.eq(PostLike::getUserId, userId);
        PostLike postLike = postLikeMapper.selectOne(lambdaQueryWrapper);
        return postLike != null;
    }
}
